package com.example.tests;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;

import java.util.Random;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.example.obj.ContactObject;
import com.example.obj.ContactSet;
public class Test_06_ContactRemoval extends TestBase{
	
	Random rnd = new Random();
	
	@BeforeMethod
	public void init(){
		if (manager.getContactHelper().getContactsCache().size() == 0) { 
			log.info("Before: Start contact removal");
			log.info("There are no contacts for removal. Try to create one");
			manager.getContactHelper().createContact(new ContactObject().setFirstName("name"));
		}
	}
	
	@Test(priority = 4)
	public void testContactCanBeDeleted() throws Exception {
		log.info("Start testContactCanBeDeleted");
		ContactSet oldContactSet = manager.getContactHelper().getContactsCache();
		assertThat(oldContactSet.size() > 0, is(true));
		log.info("Old contacts list: " + oldContactSet);
		ContactObject contact = oldContactSet.getElement(rnd.nextInt(oldContactSet.size()));	
		manager.getContactHelper().deleteContact(contact.id);		
		ContactSet newContactSet = manager.getContactHelper().getContactsCache();	
		log.info("New contacts list: " + newContactSet);
		log.info("Start assertions: size, lists' elements");
		assertThat(newContactSet.size(), equalTo(oldContactSet.size() - 1));
		assertThat(newContactSet, equalTo(oldContactSet.without(contact)));		
		log.info("Stop assertions");
	}
	
	@AfterMethod
	public void testUIConfirmWithDB(){
		log.info("After testContactCanBeDeleted");
		ContactSet contactsUI = manager.getContactHelper().getContactsUI();
		log.info("Contacts from UI: " + contactsUI);		
		ContactSet contactsDB = manager.getContactHelper().getCacheCopy();
		log.info("Contacts from DB: " + contactsDB);
		assertThat(contactsDB, equalTo(contactsUI));
	}
}
